<?php
/**
 *@file wapUser.php
 *@author Zhe.Zhou(zhouzhe@haibao.com)
 *@date 2015-10-26 下午3:19:25
 *@brief  
 */
namespace haibao\www\business;

use haibao\app\business\BusinessException;
use haibao\www\data\WapUser as WapUserData;
class WapUser extends \haibao\www\business\Base{
	/**
	 * 获取用户信息
	 * @param int $userId
	 */
	public static function getUserInfoByUserId($userId){
		if(!$userId){
			throw new BusinessException('用户Id不能为空',self::NO_LOGIN);
		}
		$wapUserData = new WapUserData();
		$userData = $wapUserData->getUserInfoByUserId($userId);
		return $userData;
	}
	/**
	 * 更新用户的个人资料
	 * @param int $userId
	 * @param array $userInfo
	 */
	public static function updateUserProfileByUserId($userId,$profile){
		if(!$userId){
			throw new BusinessException('用户Id不能为空',self::NO_LOGIN);
		}
		$wapUserData = new WapUserData();
		$userData = $wapUserData->updateUserProfileByUserId($userId, $profile);
	}
	
	public static function getPrivacyByUserId($userId){
		if(!$userId){
			throw new BusinessException('用户Id不能为空',self::NO_LOGIN);
		}
		$wapUserData = new WapUserData();
		return $wapUserData->getPrivacyByUserId($userId);
	}
	
	public static function getChinaPosition(){
		return array('北京市','上海市','安徽省','福建省','山东省','河南省','湖北省','江西省','湖南省',
				'广东省','浙江省','江苏省','天津市','河北省','山西省','内蒙古自治区','辽宁省','吉林省',
				'黑龙江省','广西壮族自治区','海南省','重庆市','香港特别行政区','澳门特别行政区','台湾省','新疆维吾尔自治区','四川省',
				'贵州省','云南省','西藏自治区','陕西省','甘肃省','青海省','宁夏回族自治区','海外','其他');
	}
	
	public static function getLocal($ip){
		$province = $local = '';
		if($ip){$province = self::getPositionByCurl($ip);}
		$provinceArr =self::getChinaPosition();
		if($province){
			foreach($provinceArr as $pro){
				if(strpos($pro,$province) !== false){
					$local = $pro;
					break;
				}
			}
		}
		return $local;
	}
	
	/**
	 * 判断被加用户是否存在
	 * 判断双方是否已经为好友
	 * @param 当前登录用户Uid：$fromUid
	 * @param 被加用户Uid：$toUid
	 * @param $flag：其中 0：$toUid不存在;1：相互已为好友;2：+关注成功
	 * @param $fromUid的好友数量：$friendNum
	 */
	public static function addAttention($fromUid,$toUid){
	    $friendNum = 0;
	    $flag = 0;
	    if(!$fromUid){
	        throw new BusinessException('用户Id不能为空',self::NO_LOGIN);
	    }
	    $myUserInfo = \haibao\user\business\user::getUserByUserId($fromUid);
	    $friendUserInfo = \haibao\user\business\user::getUserByUserId($toUid);
	    if($friendUserInfo != NULL){
	        $isFriend = self::isEachFriend($fromUid,$toUid);
	        if($isFriend){
	            $flag = 1;
	        }else{
	           self::addFridend($fromUid,$myUserInfo->username,$toUid,$friendUserInfo->username);
	           $flag = 2;
	        }
	    } else {
	        $flag = 0;
	    }
	    return $flag;
	}
	/**
	 * 相互是否为好友
	 * @param 当前用户Uid $fromUid
	 * @param 被加用户Uid $toUid
	 */
	public static function isEachFriend($fromUid,$toUid){
	    $wapUserData = new WapUserData();
	    return $wapUserData->isEachFriend($fromUid,$toUid);
	}
	/**
	 * 添加好友
	 * @param 当前用户Uid $fromUid
	 * @param 被加用户Uid $toUid
	 */
	public static function addFridend($fromUid,$myUserName,$toUid,$friendUserName){
	    $wapUserData = new WapUserData();
	    return $wapUserData->addFridend($fromUid,$myUserName,$toUid,$friendUserName);
	}
	
	/**
	 * 上传控件传入的图片
	 * @param array $useData [uid,data]
	 * @param FILE $file
	 * @throws BusinessException
	 * @return string
	 */
	public static function uploadAvatar($useData,$file){
		if(!$useData['uid']){
			throw new BusinessException('用户Id不能为空',self::NO_LOGIN);
		}
		$avatar = $file['tmp_name'];
		$userAvatar = array();
		$userAvatar['avatar'] =  ltrim(self::saveAvatar($useData, file_get_contents($avatar), '/avatar/'),'/');
		$userAvatar['avatar_md5'] =  md5($userAvatar['avatar']);
		$wapUserData = new WapUserData();
		$wapUserData->updateAvatarByUid($useData['uid'],$userAvatar);
	}
	
	/**
	 * 根据用户id获取用户真实头像地址
	 */
	private static function getAvatarByUserId($userId, $size = 'big', $type = ''){
        $size = in_array($size, array('big', 'middle', 'small')) ? $size : 'big';
        $userId = abs(intval($userId));
        $userId = sprintf("%09d", $userId);
        $dir1 = substr($userId, 0, 3);
        $dir2 = substr($userId, 3, 2);
        $dir3 = substr($userId, 5, 2);
        $typeadd = $type == 'real' ? '_real' : '';
        return  $dir1.'/'.$dir2.'/'.$dir3.'/'.substr($userId, -2).$typeadd."_avatar_$size.jpg";
    }
    
    /**
     * 保存用户头像
     */
    public static function saveAvatar($useData, $stream, $uploadFile){
    	$ext = self::getImageExt($stream);
    	$avatarPath = $uploadFile.self::getAvatarByUserId($useData['uid']);
    	$savePath = self::getAbsolutePath($avatarPath);
    	self::createDir($savePath);
    	file_put_contents($savePath, $stream);
    	
    	$sizeArr = array(
    		'small' =>'48*48',
    		'middle' => '120*120',
    		'big' => '200*200'
    	);
    	foreach ($sizeArr as $type=>$size){
    		$path = $uploadFile.self::getAvatarByUserId($useData['uid'], $type);
    		$typePath = self::getAbsolutePath($path);
    		list($width, $height) = explode('*', $size);
    		self::createDir($typePath);
    		self::reloadImageByCoor($savePath, $typePath, $width, $height,json_decode($useData['data']));
    	}
    	return $avatarPath;
    }
    
    /**
     * 根据二进制流判断图片格式
     */
    private static function getImageExt($stream){
    	$jfif_exif = substr($stream, 0, 100);
    	if(strpos($jfif_exif, 'JFIF') || strpos($jfif_exif, 'JPEG') || strpos($jfif_exif, 'JPG') || strpos($jfif_exif, 'Exif') || strpos($jfif_exif, 'EXIF')){
    		$ext = '.jpg';
    	}else if(strpos($jfif_exif, 'PNG')){
    		$ext = '.png';
    	}else if(strpos($jfif_exif, 'GIF')){
    		$ext = '.gif';
    	}else{
    		$ext = '.jpg';
    	}
    	return $ext;
    }
    
    /**
     * 获取保存图片的绝对路径
     */
    private static function getAbsolutePath($path){
    	return \haibao\frame\Environment::path() . $path;
    }
    
    /**
     * 创建文件保存路径
     */
    private static function createDir($path){
    	$path = pathinfo( $path );
    	return is_writable($path['dirname']) ?: mkdir($path['dirname'], 750, true);
    }
    
    /**
     * 上传裁剪后的头像
     * @param string $sourcePath		原始图片的位置
     * @param string $toPath			图片上传的位置
     * @param int $targetWidth			目标宽度
     * @param int $targetHeight			目标高度
     * @param array $coor				坐标信息
     * @return boolean
     */
    private static function reloadImageByCoor($sourcePath,$toPath,$targetWidth,$targetHeight,$coor){
    	$sourceInfo = getimagesize($sourcePath);
    	$OrgWidth = $sourceInfo[0];
    	$OrgHeight = $sourceInfo[1];
    	$OrgMime = $sourceInfo['mime'];
    	
    	switch ($OrgMime) {
    		case 'image/gif':
    			$sourceImage = imagecreatefromgif($sourcePath);
    			break;
    		case 'image/jpeg':
    			$sourceImage = imagecreatefromjpeg($sourcePath);
    			break;
    		case 'image/png':
    			$sourceImage = imagecreatefrompng($sourcePath);
    			break;
    		default:
    			return false;
    			break;
    	}
    	
    	$targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
    	imagecopyresampled($targetImage, $sourceImage, 0, 0, $coor->x, $coor->y, $targetWidth, $targetHeight, $coor->width, $coor->height);
    	switch ($OrgMime) {
    		case 'image/gif':
    			imagegif($targetImage, $toPath);
    			break;
    		case 'image/jpeg':
    			imagejpeg($targetImage, $toPath);
    			break;
    		case 'image/png':
    			imagepng($targetImage, $toPath);
    			break;
    	}
    	imagedestroy($sourceImage);
    	imagedestroy($targetImage);
    }
    
    private static function getPositionByCurl($ip){
    	$resData = '';
    	$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, "http://freeapi.ipip.net/".$ip);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch, CURLOPT_TIMEOUT,10);
    	curl_setopt($ch, CURLOPT_HEADER, 0);
    	
    	$output = curl_exec($ch);
    	curl_close($ch);
    	
    	$positions = json_decode($output);
    	if(!empty($positions)){
    		$resData = $positions[1];
    	}
    	return $resData;
    }
}